# -*- coding: utf-8 -*-
from wx._core import wxAssertionError
import decimal
import re
import wx
import wx.lib.plot as wxplot
import wx.xrc
import wx.adv
import os
import wx.richtext
import time
import threading
import random
import requests
import json
import datetime
import base64

import mydata
import classrun
import myimage
import mysqldb


class setshangping(wx.Frame):
    def __init__(self, parent,id,name,price,ations,pathfil):
        wx.Frame.__init__(self,parent, title="商品信息",pos = wx.DefaultPosition,size = wx.Size(500,300),style = wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
        pathfil = os.path.abspath(pathfil)
        def img_dataset(img_data,fx,m):
            if m:
                with open(m,"rb") as redata:
                    img_data = classrun.pngSize(50,50,redata.read())
            return wx.StaticBitmap(self,bitmap=img_data,pos=fx,size = (50,50))

        if os.path.isfile(pathfil) and len(pathfil) > 1:
            list_file = os.listdir(os.path.dirname(pathfil))
            try:
                self.bitmap1 = img_dataset(None,(90,5),os.path.join(os.path.dirname(pathfil),list_file[0]))
                self.bitmap2 = img_dataset(None,(230,5),os.path.join(os.path.dirname(pathfil),list_file[1]))
                self.bitmap3 = img_dataset(None,(360,5),os.path.join(os.path.dirname(pathfil),list_file[2]))
            except Exception as e:
                print(e)
        else:
            bytesdata = base64.b64decode(bytes(myimage.xigua))
            self.bitmap1 = img_dataset(classrun.pngSize(50,50,bytesdata),(90,5),None)
            self.bitmap2 = img_dataset(classrun.pngSize(50,50,bytesdata),(230,5),None)
            self.bitmap3 = img_dataset(classrun.pngSize(50,50,bytesdata),(360,5),None)

        self.parent = parent
        self.myid = id
        self.filepick2 = wx.FilePickerCtrl(self,path=pathfil,message="选择图片",wildcard=u'*.jpg',pos=(240,60),size = (30,20))
        wx.StaticText(self,label="序号:      "+str(id),pos=(150,100),size = (150,24))
        wx.StaticText(self,label="名称",pos=(150,130),size = (24,24))
        wx.StaticText(self,label="规格",pos=(150,160),size = (24,24))
        wx.StaticText(self,label="价格",pos=(150,190),size = (24,24))
        self.name = wx.TextCtrl(self,value=name,pos=(200,130),size = (150,24))
        self.ations = wx.TextCtrl(self,value=ations,pos=(200,160),size = (150,24))
        self.price = wx.TextCtrl(self,value=str(price),pos=(200,190),size = (150,24))
        self.buttonsou = wx.Button(self, label="修改",pos=(100,225),size = (300,28))
        self.buttonrem = wx.Button(self, label="删除",pos=(30,120),size = (50,50))
        self.buttonsou.Bind(wx.EVT_BUTTON, lambda evt, mark=True : self.setupdate(evt,mark))
        self.buttonrem.Bind(wx.EVT_BUTTON, lambda evt, mark=False : self.setupdate(evt,mark))
        self.filepick2.Bind(wx.EVT_FILEPICKER_CHANGED,self.updataimg)
        self.Centre()
        #print(dir(self.parent))

    def updataimg(self,eve):
        with open(self.filepick2.GetPath(),"rb") as imgdata:
            dataimg = imgdata.read()
        self.parent.dict_app[self.myid].SetBitmap(classrun.pngSize(50,50,dataimg))
        #self.bitmap1.SetBitmap()
        self.bitmap2.SetBitmap(classrun.pngSize(50,50,dataimg))
        #self.bitmap2.SetBitmap()

    def setupdate(self,eve,mak):
        if mak:
            txt1 = self.name.GetValue()
            txt2 = self.ations.GetValue()
            txt3 = self.price.GetValue()
            ret = mysqldb.mysql.update_data('inventory',"name='{}',price='{}',ations='{}',path='{}'".format(txt1,txt3,txt2,self.filepick2.GetPath()),"myid={}".format(self.myid))
            if ret:
                self.Close()
        else:
            answer = wx.MessageBox("确定删除商品？", "删除提示",wx.YES_NO | wx.CANCEL, self)
            if answer == wx.YES:
                ret = mysqldb.mysql.delete_data('inventory',"myid={}".format(self.myid))
                if ret:
                    print(list(self.parent.dict_app))
                    self.parent.dict_app[self.myid].Destroy()
                    self.parent.dict_app.pop(self.myid)
                    x=10;y=10
                    for ap in self.parent.dict_app:
                        self.parent.dict_app[ap].SetPosition((x,y))
                        x += 55
                        if x >840:
                            x = 10
                            y += 55
                    #postiom = self.parent.dict_app[self.myid].GetPosition()
                    #self.parent.dict_app[list(self.parent.dict_app)[-1]].SetPosition(postiom)
                    #self.parent.dict_app[self.myid].Destroy()
                    #self.parent.dict_app.pop(self.myid)
                    #self.parent.Refresh()
                    self.Close()



class MainWindow(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self,parent, title="商品结算",pos = wx.DefaultPosition,size = wx.Size(960,540),style = wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX) )
        fontxt = wx.Font(15, wx.FONTFAMILY_SCRIPT, wx.NORMAL, wx.FONTWEIGHT_MEDIUM, False, 'Consolas') # 字体设置
        self.order = "" # 订单号初始化
        self.price = decimal.Decimal.from_float(0.0) # 价格初始化
        self.list_goods = wx.ListCtrl(self,style=wx.LC_REPORT,pos=(10,10),size = (320,450))
        self.list_goods.InsertColumn(0, "商品序号")
        self.list_goods.InsertColumn(1, "商品名称")
        self.list_goods.InsertColumn(2, "商品规格")
        self.list_goods.InsertColumn(3, "商品价格")
        self.button1 = wx.Button(self, label="删除商品",pos=(10,465),size = (120,30))
        self.button2 = wx.Button(self, label="结算",pos=(210,465),size = (120,30))
        wx.StaticText(self,label="价格:",pos=(340,30),size = (50,30)).SetFont(fontxt)
        self.sum_int = wx.StaticText(self,label="0",pos=(400,30),size = (50,30))
        self.money = wx.TextCtrl(self, value="",pos=(340,70),size = (150,24))
        self.spin = wx.SpinCtrl(self,pos=(342,100),size = (50,24),min=1,max=1000)
        self.button3 = wx.Button(self, label="额外",pos=(450,100),size = (40,24))
        self.sum_han = wx.StaticText(self,label="零",pos=(340,200),size = (100,30))
        wx.StaticText(self,label="现金找零:",pos=(340,350),size = (50,30)).SetFont(fontxt)
        self.lingqian = wx.StaticText(self,label="0",pos=(440,350),size = (50,30))
        self.inputint = wx.TextCtrl(self, value="",pos=(340,380),size = (150,24))
        self.button4 = wx.Button(self, label="找零",pos=(340,410),size = (150,30))
        self.richtextlog = wx.richtext.RichTextCtrl(self,value=time.strftime("%Y-%m-%d %H:%M:%S"),pos=(500,10),size = (435,450))
        self.strtext1 = wx.TextCtrl(self, value="",pos=(510,15),size = (150,30),style=wx.TE_PROCESS_ENTER)
        self.strtext2 = wx.StaticText(self,label="<-点击里面开始扫码",pos=(660,20),size = (100,30))
        self.button5 = wx.Button(self, label="关闭日志",pos=(500,465),size = (200,30))
        self.button6 = wx.Button(self, label="加载日志",pos=(735,465),size = (200,30))
        self.lingqian.SetFont(fontxt)
        self.sum_int.SetFont(fontxt)
        self.sum_han.SetFont(fontxt)
        self.strtext2.SetFont(fontxt)

        self.button1.Bind(wx.EVT_BUTTON, self.del_goods)
        self.button2.Bind(wx.EVT_BUTTON, lambda evt, mark=True : self.settlement(evt,mark))
        self.button3.Bind(wx.EVT_BUTTON, self.zhaoButton)
        self.button4.Bind(wx.EVT_BUTTON, lambda evt, mark=False : self.settlement(evt,mark))
        self.button5.Bind(wx.EVT_BUTTON, self.endButton)
        self.button6.Bind(wx.EVT_BUTTON, self.add_log)

        #self.list_goods.Bind(wx.EVT_LIST_ITEM_SELECTED, lambda evt, mark=True : self.selecet(evt,mark))
        #self.list_goods.Bind(wx.EVT_LIST_ITEM_DESELECTED, lambda evt, mark=False : self.selecet(evt,mark))
        
        self.strtext1.Bind(wx.EVT_TEXT_ENTER, lambda evt, mark=False : self.add_goods(evt,mark))
        self.Bind(wx.EVT_KEY_DOWN, lambda evt, mark=True : self.add_goods(evt,mark))

        self.strtext1.Bind(wx.EVT_KEY_DOWN, lambda evt, mark=False : self.add_goods(evt,mark))
        self.list_goods.Bind(wx.EVT_KEY_DOWN, lambda evt, mark=True : self.add_goods(evt,mark))

        self.richtextlog.SetStyle(0,20,wx.TextAttr("white","black"))
        self.richtextlog.SetDefaultStyle(wx.TextAttr("red","green"))
        self.Centre()
        self.strtext1.Show(False)
        self.strtext2.Show(False)

    def settlement(self,eve,mak):
        if mak and float(self.price)!=0.0:
            msg = ''
            for i in mydata.CACHE:
                msg += str((int(i),mydata.CACHE[i][0],mydata.CACHE[i][1]))
            mssage = " 金额: " + str(float(self.price)) + "元  " + msg
            #print(mssage)
            self.setmak(time.strftime("%Y-%m-%d %H:%M:%S"),mssage,False)
            #print(time.strftime("%Y-%m-%d %H:%M:%S"))
            m = time.gmtime()
            msg = "null,{},{},{},'{}','{}','{}'".format(m.tm_year,m.tm_mon,m.tm_mday,time.strftime("%H:%M:%S"),str(float(self.price)),msg)
            ret = mysqldb.mysql.insert_data('mylog',"ID,time_year,time_month,time_day,time_datetime,mymoney,content",msg)
            self.list_goods.DeleteAllItems()
            self.setmak("零","0",True)
            self.money.SetValue("")
            self.spin.SetValue(0)
            self.price = decimal.Decimal.from_float(0.0)
            mydata.CACHE = {}
        else:
            try:
                sam = int(self.inputint.GetValue())
                suu = sam - int(self.price)
                self.lingqian.SetLabel(str(suu))
            except ValueError:
                self.setmak(time.strftime("%Y-%m-%d %H:%M:%S"),"不能填入非数字",False)

    def zhaoButton(self,eve):
        try:
            moneyy = float(self.money.GetValue()) * self.spin.GetValue()
            monecc = "100" + str(int(self.money.GetValue())) + str(self.spin.GetValue())
            self.list_goods.Append((monecc,"额外附加",self.spin.GetValue(),str(moneyy)))
            classrun.dict_update(mydata.CACHE,(monecc,moneyy),"add")
            self.price += decimal.Decimal.from_float(moneyy)
            h,i = classrun.ch_zh_han(self.price)
            self.setmak(h,i,True)
        except ValueError:
            self.setmak(time.strftime("%Y-%m-%d %H:%M:%S"),"不能填入非数字",False)

    def endButton(self,eve):
        if self.button5.Label == "关闭日志":
            self.richtextlog.Show(False)
            self.strtext1.Show(True)
            self.strtext2.Show(True)
            self.button5.SetLabel("打开日志")
        else:
            self.richtextlog.Show(True)
            self.strtext1.Show(False)
            self.strtext2.Show(False)
            self.button5.SetLabel("关闭日志")

    def del_goods(self, e):
        try:
            goodssum = self.list_goods.GetItemCount()
            for i in range(0,goodssum):
                m = i - (goodssum - self.list_goods.GetItemCount())
                if self.list_goods.IsSelected(m):
                    id_del = mydata.CACHE[self.list_goods.GetItemText(m)][0]
                    classrun.dict_update(mydata.CACHE,(self.list_goods.GetItemText(m),id_del),"del")
                    self.list_goods.DeleteItem(m)
                    self.price -= decimal.Decimal.from_float(id_del)
            if int(self.price) == 0:
                self.price = decimal.Decimal.from_float(0.0)
                self.setmak("零","0",True)
            else:
                h,i = classrun.ch_zh_han(self.price)
                self.setmak(h,i,True)
        except Exception as e:
            classrun.erre_log(e)

    def add_goods(self,eve,mak):
        if mak:
            if eve.GetRawKeyFlags() == 1835009:
                self.updategoods()
            elif str(eve.GetRawKeyFlags()) in mydata.WX_KEY_DICT:
                self.order += mydata.WX_KEY_DICT[str(eve.GetRawKeyFlags())]
        else:
            if eve.GetRawKeyFlags() == 1835009:
                self.order = self.strtext1.GetLineText(0) 
                self.updategoods()
                self.strtext1.SetValue("")

    def add_log(self,eve):
        self.button6.Enable(False)
        x,y = self.GetPosition()
        x += 660
        feilpath(self,x,y).Show(True)

    def setmak(self,h,i,mak):
        if mak:
            self.sum_han.SetLabel(h)
            self.sum_int.SetLabel(i)
        else:
            self.richtextlog.AddParagraph(h + " : " + i)
            self.richtextlog.AppendText(" ")
            self.richtextlog.ShowPosition(-1)

    def updategoods(self):
        if len(self.order) > 5 and self.order in mydata.GOODS_DATA:
            self.list_goods.Append((mydata.GOODS_DATA[self.order]['id'], mydata.GOODS_DATA[self.order]['name'], mydata.GOODS_DATA[self.order]['ations'], mydata.GOODS_DATA[self.order]['price']))
            classrun.dict_update(mydata.CACHE,(mydata.GOODS_DATA[self.order]['id'],mydata.GOODS_DATA[self.order]['price']),"add")
            self.price += decimal.Decimal.from_float(mydata.GOODS_DATA[self.order]['price'])
            h,i = classrun.ch_zh_han(self.price)
            self.setmak(h,i,True)
        else:
            print(self.order)
            self.setmak(time.strftime("%Y-%m-%d %H:%M:%S"),"商品库里没有这个商品 " + self.order +"正在联网添加中。。。",False)
            classrun.mythread(self,classrun.httpadd,int(self.order)).start()
        self.order = ""

    def LogMesrun(self,code):
        print(code)


class Page2(wx.Panel):
    def __init__(self,parent,listapp):
        wx.Panel.__init__(self, parent)
        self.parent = parent
        x = 10
        y = 10
        self.dict_app = {}
        for i in listapp:
            if os.path.isfile(os.path.abspath(i[1])) and len(i[1]) > 1:
                with open(os.path.abspath(i[1]),"rb") as imgdata:
                    bytesdata = imgdata.read()
            else:
                bytesdata = base64.b64decode(bytes(myimage.xigua))
            img = classrun.pngSize(50,50,bytesdata)
            self.BitmapButtons = wx.BitmapButton(self, bitmap=img, pos=(x,y), size = (50,50))
            self.BitmapButtons.Bind(wx.EVT_BUTTON,lambda evt, mark=i : self.openapp(evt,mark))
            self.dict_app.update({i[0]:self.BitmapButtons})
            x += 55
            if x >840:
                x = 10
                y += 55

    def openapp(self,eve,id):
        ret = mysqldb.mysql.select_data('name,price,ations,path',"inventory WHERE myid='{}' LIMIT 1".format(id[0]))
        
        if ret:
            setshangping(self,id[0], ret[0][0],ret[0][1],ret[0][2],ret[0][3]).Show(True)
        else:
            print(ret)


class shangping(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self,parent, title="商品库",pos = wx.DefaultPosition,size = wx.Size(960,540),style = wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
        self.appPagename = 0
        self.mynotebook = wx.Notebook(self,size = wx.Size(960,400))
        ret = mysqldb.mysql.select_data('myid,path','inventory LIMIT 50 OFFSET {}'.format(self.appPagename))
        if ret:
            self.mynotebook.AddPage(Page2(self.mynotebook,ret),str(self.appPagename))
            self.appPagename += 50
        self.buttonabb = wx.Button(self, label="上一页",pos=(10,450),size = (56,30))
        self.buttonadd = wx.Button(self, label="下一页",pos=(70,450),size = (56,30))
        self.buttonend = wx.Button(self, label="加载",pos=(130,450),size = (56,30))
        self.buttonsou = wx.Button(self, label="搜索",pos=(880,458),size = (56,28))
        self.text = wx.TextCtrl(self, value="",pos=(660,460),size = (210,24))
        self.rettext = wx.StaticText(self,label="",pos=(400,450),size = (100,30))
        self.sousuo = wx.Choice(self, choices=["序号","名称"],pos=(610,460),size = (50,24))
        self.sousuo.SetSelection(0)
        self.buttonadd.Bind(wx.EVT_BUTTON, lambda evt, mark=True : self.abbapp(evt,mark))
        self.buttonabb.Bind(wx.EVT_BUTTON, lambda evt, mark=False : self.abbapp(evt,mark))
        self.buttonend.Bind(wx.EVT_BUTTON, self.addapp)
        self.buttonsou.Bind(wx.EVT_BUTTON, self.addend)
        self.mynotebook.Bind(wx.EVT_KEY_DOWN,self.upkey)
        self.Bind(wx.EVT_KEY_DOWN,self.upkey)
        self.Centre()

    def upkey(self,eve):
        self.rettext.SetLabel("")
        if eve.GetRawKeyFlags() == 21823489:
            self.abbapp(eve,True)
        elif eve.GetRawKeyFlags() == 21692417:
            self.abbapp(eve,False)
        elif eve.GetRawKeyFlags() == 1835009:
            self.addend(eve)
        elif eve.GetRawKeyFlags() == 21495809:
            self.sousuo.SetSelection(0)
        elif eve.GetRawKeyFlags() == 22020097:
            self.sousuo.SetSelection(1)

    def addend(self,eve):
        self.rettext.SetLabel("")
        myid = self.text.GetValue()
        ret = mysqldb.mysql.select_data('name,price,ations,path',"inventory WHERE myid='{}' LIMIT 1".format(myid))
        if ret:
            def sou_app(n):
                if int(myid) in self.mynotebook.GetCurrentPage().dict_app:
                    return 
                else:
                    try:
                        self.mynotebook.SetSelection(n)
                        return sou_app(n+1)
                    except:
                        return
            sou_app(0)
            setshangping(self.mynotebook.GetCurrentPage(),int(myid), ret[0][0],ret[0][1],ret[0][2],ret[0][3]).Show(True)
        else:
            self.rettext.SetLabel("数据库没有找到到商品, 联网添加中...")
            classrun.mythread(self,classrun.httpadd,int(myid)).start()

    def abbapp(self,eve,mak):
        self.rettext.SetLabel("")
        try:
            if mak:
                self.mynotebook.SetSelection(self.mynotebook.GetSelection()+1)
            else:
                self.mynotebook.SetSelection(self.mynotebook.GetSelection()-1)
        except wxAssertionError:
            if mak:
                self.rettext.SetLabel("已在最后一页")
            else:
                self.rettext.SetLabel("已在第一页")

    def addapp(self,eve):
        self.rettext.SetLabel("")
        self.buttonend.Enable(False)
        try:
            ret = mysqldb.mysql.select_data('myid,path','inventory LIMIT 50 OFFSET ' + str(self.appPagename))
            if ret:
                self.mynotebook.AddPage(Page2(self.mynotebook,ret),str(self.appPagename))
                self.appPagename +=50
                self.buttonend.Enable(True)
            else:
                wx.MessageBox("已加载完毕",caption="提示")
                self.buttonend.Show(False)
        except:
            wx.MessageBox("已加载完毕",caption="提示")
            self.buttonend.Show(False)

    def LogMesrun(self,code):
        if code[0]:
            while True:
                try:
                    self.mynotebook.SetSelection(self.mynotebook.GetSelection()+1)
                except wxAssertionError:
                    break
            wind = self.mynotebook.GetCurrentPage()
            x,y = wind.dict_app[list(wind.dict_app)[-1]].GetPosition()
            x += 55
            if x >840:
                x = 10
                y += 55
            bytesdata = base64.b64decode(bytes(myimage.xigua))
            img = classrun.pngSize(50,50,bytesdata)
            BitmapButton = wx.BitmapButton()
            BitmapButton.Create(wind, bitmap=img, pos=(x,y), size = (50,50))
            BitmapButton.Bind(wx.EVT_BUTTON, lambda evt, mark=(code[1],'') : wind.openapp(evt,mark))
            wind.dict_app.update({code[1]:BitmapButton})
        else:
            self.rettext.SetLabel(code[1])


class feilpath(wx.Frame):
    def __init__(self, parent,x,y):
        wx.Frame.__init__(self, parent, title="路径", pos=(x,y), size=( 300,300 ))
        self.parent = parent
        self.m_genericDirCtrl2 = wx.adv.CalendarCtrl(self, date=wx.DefaultDateTime,size=( 300,300 ))
        self.m_genericDirCtrl2.Bind(wx.adv.EVT_CALENDAR,self.add_logs)
        self.Bind(wx.EVT_CLOSE,self.onclose)

    def onclose(self,eve):
        self.parent.button6.Enable(True)
        self.Destroy()

    def add_logs(self,eve):
        my_time = self.m_genericDirCtrl2.GetDate()
        #print(dir(my_time))
        my_time = str(my_time).split(" ")[0].split("/")#.replace("/","-")
        #def set_str(m,n):
        #    s = m.split("-")
        #    if n == len(s):
        #        return m
        #    elif len(s[n]) == 1:
        #        m = "-".join(["0" + i if s[n] == i else i for i in s])
        #    return set_str(m,n+1)
        #my_time = set_str(my_time,0)
        ret = mysqldb.mysql.select_data("time_datetime,mymoney,content","mylog WHERE time_year={} AND time_month={} AND time_day={}".format(my_time[0],my_time[1],my_time[2]))
        print(my_time,ret)
        if ret:
            self.parent.richtextlog.AddParagraph("-"*24+str(my_time)+"-"*24)
            self.parent.richtextlog.AppendText(" ")
            for i in ret:
                self.parent.richtextlog.AddParagraph(str(i))
                self.parent.richtextlog.AppendText(" ")
            self.parent.richtextlog.AddParagraph("-"*24+str(my_time)+"-"*24)
        else:
            self.parent.richtextlog.AddParagraph("没有查到 " + str(my_time) + " 的日志")
        self.parent.richtextlog.AppendText(" ")
        self.parent.richtextlog.ShowPosition(-1)
        self.parent.button6.Enable(True)
        self.Close()


class MyFramemain( wx.Frame ):
    def __init__( self, parent):
        wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = "开源地址；https://gitee.com/xuewumeng/Project", pos = wx.DefaultPosition, size = wx.Size( 500,300 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
        self.m_button1 = wx.Button( self, wx.ID_ANY, u"编码库",pos=(50,50))
        self.m_button2 = wx.Button( self, wx.ID_ANY, u"报表",pos=(50,80))
        self.m_button3 = wx.Button( self, wx.ID_ANY, u"扫码",pos=(50,110))
        #self.Layout()
        self.Centre( wx.BOTH )
        self.m_button3.Bind(wx.EVT_BUTTON, lambda evt, mark=MainWindow : self.starun(evt,mark))
        self.m_button2.Bind(wx.EVT_BUTTON, lambda evt, mark=myView : self.starun(evt,mark))
        self.m_button1.Bind(wx.EVT_BUTTON, lambda evt, mark=shangping : self.starun(evt,mark))

    def starun(self,eve,appweb):
        appweb(None).Show(True)

    def updatepath(self,eve):
        path = self.m_textCtrl3.GetValue()
        print(path)


class myView( wx.Frame ):
    def __init__( self, parent ):
        wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = "销售小时报表", pos = wx.DefaultPosition, size = wx.Size( 920,540 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
        self.pane = wx.Panel(self)
        self.mycolour = ['red','orange','yellow','green','cyan','blue','purple','black']
        self.pane.SetBackgroundColour("white")
        self.Button1 = wx.Button(self.pane,label="折线图",pos=(10,410))
        self.Button2 = wx.Button(self.pane,label="查询",pos=(700,410))
        self.choice1 = wx.Choice(self.pane,choices=['红色','橙色','黄色','绿色','青色','蓝色','紫色','黑色'],pos=(640,410))
        self.choice1.SetSelection(0)
        self.datem = wx.adv.DatePickerCtrl(self.pane,pos=(780,410))
        self.Button1.Bind(wx.EVT_BUTTON,  lambda evt, mark=True : self.redraw(evt,mark))
        self.Button2.Bind(wx.EVT_BUTTON,self.update)
        self.plotter = wxplot.PlotCanvas(self.pane)
        self.plotter.SetInitialSize(size=(900, 400))
        mytm = time.gmtime()
        self.data = self.get_data(mytm.tm_year,mytm.tm_mon,mytm.tm_mday)
        line=wxplot.PolyBars(self.data[0],fillcolour=self.mycolour[self.choice1.Selection])
        gc= wxplot.PlotGraphics([line], self.data[1]+"元", '', '')
        self.plotter.ySpec = 10
        self.plotter.xSpec = 24
        self.plotter.tickLength = (0,0)
        self.plotter.Draw(gc)
        self.Centre()


    def redraw(self, eventm,mak):
        if self.Button1.GetLabel() == "折线图":
            line= wxplot.PolyLine(self.data[0], colour=self.mycolour[self.choice1.Selection], width=2)
            if mak:
                self.Button1.SetLabel("条形图")
        else:
            line=wxplot.PolyBars(self.data[0],fillcolour=self.mycolour[self.choice1.Selection])
            if mak:
                self.Button1.SetLabel("折线图")
        gc= wxplot.PlotGraphics([line], self.data[1]+"元", '', '')
        self.plotter.Draw(gc)

    def update(self, event):
        my_time = str(self.datem.GetValue()).split(" ")[0].split("/")
        self.data = self.get_data(my_time[0],my_time[1],my_time[2])
        self.redraw(event,False)

    def get_data(self,y,m,d):
        ret = mysqldb.mysql.select_data("time_datetime,mymoney","mylog WHERE time_year={} AND time_month={} AND time_day={}".format(y,m,d))
        if ret:
            mydict = {}
            mony = int(sum(map(lambda x:float(x[1]), ret)))
            for i in ret:
                classrun.dict_date(mydict,(i[0].split(":")[0],int(float(i[1]))))
            lism = [(i,mydict[i]) for i in mydict]
            return ([(0, 0)] + [(int(lism[0][0])-1,0)] + lism + [(int(lism[-1][0])+1,0)] + [(24, 0)],str(mony))
        else:
            return ([(0, 0),(24, 0)],str(0))


app = wx.App(False)
MyFramemain(None).Show(True)
app.MainLoop()